package com.company.netty.demo.NIO.ChannelDemos;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 使用ByteBuffer和FileChannel 的read 和write方法完成文件的复制 file.txt to file1.txt
 *
 * todo: 18
 * */
public class FileChannelCopyTest {

    /**
     * 使用channel复制完成文件复制
     * */
//    public static void main(String[] args) throws Exception{
//
//        File fileSrc = new File("file.txt");
//
//        FileInputStream fis = new FileInputStream(fileSrc);
//
//        FileChannel fileChannelSrc = fis.getChannel();
//
//        File fileDest = new File("file1.txt");
//
//        FileOutputStream fileOutputStream = new FileOutputStream(fileDest);
//        FileChannel fileChannelDest = fileOutputStream.getChannel();
//
//        fileChannelSrc.transferTo(0, fileChannelSrc.size(), fileChannelDest);
//
//        fis.close();
//        fileOutputStream.close();
//
//    }

    /**
     * 使用FileChannel的读、写完成文件复制  file.txt to file2.txt
     * */
    public static void main(String[] args) throws Exception{
        File fileSrc = new File("file.txt");

        FileInputStream fileInputStreamSrc = new FileInputStream(fileSrc);

        FileChannel inputStreamSrcChannel = fileInputStreamSrc.getChannel();

        //将文件写入到byteBuffer中
        ByteBuffer byteBufferSrc = ByteBuffer.allocate((int) fileSrc.length());

        //读取数据到buffer中
        inputStreamSrcChannel.read(byteBufferSrc);

        //position重置，方便后面读数据
        byteBufferSrc.flip();

        //实例化目标文件IO
        File fileDest = new File("file2.txt");

        FileOutputStream fileOutputStreamDest = new FileOutputStream(fileDest);

        //IO转channel，实际就是打通io与channel的关系
        FileChannel outputStreamDestChannel = fileOutputStreamDest.getChannel();

        //将buffer中的数据写到channel中，channel自动写入到文件中
        outputStreamDestChannel.write(byteBufferSrc);

        fileOutputStreamDest.close();
        fileInputStreamSrc.close();


    }

}
